/*******************************************************************************
 * Copyright (c) 2001, 2002 Boris Pruessmann and others. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Common Public License v0.5 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors: Boris Pruessmann - Initial implementation.
 ******************************************************************************/
package net.sourceforge.perforce.ui.action;

import net.sourceforge.perforce.core.PerforceException;
import net.sourceforge.perforce.core.resources.LocalResource;
import net.sourceforge.perforce.ui.NewFilesDialog;
import net.sourceforge.perforce.ui.internal.AddToSourceControlRunnable;

import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;

/**
 * @version $Revision: 488 $
 * @author <a href="mailto:bpruessmann@users.sourceforge.net">Boris
 *         Pruessmann</a>
 */
public class AddToSourceControlAction extends PerforceAction {
  //----------------------------------------------------------------------------
  // -- Public Methods

  private IResource[] selectedResources;

  @Override
  public void run(IAction action) {
    if (checkForDialog()) {
      NewFilesDialog dlg =
          new NewFilesDialog(Display.getDefault().getActiveShell(), getSelectedResources());
      if (dlg.open() != Window.OK) return;
      selectedResources = dlg.getSelectedResources();
    }
    addSelectedResources();
    selectedResources = null;
  }

  @Override
  protected IResource[] getSelectedResources() {
    if (selectedResources == null) return super.getSelectedResources();
    return selectedResources;
  }

  // ---------------------------------------------------------------------------
  // Protected Methods

  private boolean checkForDialog() {
    IResource[] resources = getSelectedResources();
    for (int i = 0; i < resources.length; i++)
      if (resources[i].getType() != IResource.FILE) return true;
    return false;
  }

  private void addSelectedResources() {
    run(new AddToSourceControlRunnable(getProviderMapping()), PROGRESS_DIALOG);
  }

  /**
   * @see PerforceAction#isEnabled() should be enabled if any resource selected,
   *      or any descendant of a selected resource can be added.
   **/
  @Override
  protected boolean isEnabled() throws PerforceException {
    IResource[] resources = getSelectedResources();
    if (resources.length == 0) {
      return false;
    }

    return LocalResource.oneOrMoreResourcesNeedsAdding(resources);
  }
}
